function createSelectType() {
    return $('<select></select>')
        .append('<option value="bit">Bit type</option> ')
        .append('<option value="float">Float type</option> ')
        .append('<option value="datetime">Datetime type</option> ')
        .append('<option value="varchar">Varchar type</option> ')
        .append('<option value="int">Int type</option> ');
}

function createFromAllRangeRowChoice(choiceName) {
    return '<tr>' +
        '       <td><input class="allRangeRadio" type="radio" checked value="fromAllRange" name="' + choiceName + '"></td>' +
        '       <td colspan="2"><span class="allRangeRadioLabel">From all range</span></td>' +
        '       <td></td>' +
        '   </tr>'
}
function createNullRowChoice(choiceName) {
    return '<tr>' +
        '       <td><input class="nullRadio" type="radio" value="null" name="' + choiceName + '"></td>' +
        '       <td colspan="2"><span class="nullRadioLabel">Null</span></td>' +
        '       <td></td>' +
        '   </tr>'
}
function createFromSourceRowChoice(choiceName) {
    return '<tr>' +
        '       <td><input class="fromSourceRadio" type="radio" value="fromSource" name="' + choiceName + '"></td>' +
        '       <td><span class="fromSourceRadioLabel">From source</span></td>' +
        '       <td><div class="params">' +
        '           <table>' +
        '               <tr>' +
        '                   <td>Source: </td>' +
        '                   <td><input id="paramSource" type="text"></td>' +
        '               </tr>' +
        '               <tr>' +
        '                   <td>Separator: </td>' +
        '                   <td><input id="paramSeparator" type="text"></td>' +
        '               </tr>' +
        '               <tr>' +
        '                   <td>Randomize: </td>' +
        '                   <td><input id="paramRandom" type="checkbox"></td>' +
        '               </tr>' +
        '               <tr>' +
        '                   <td>Wrap: </td>' +
        '                   <td><input id="paramWrap" type="text"></td>' +
        '               </tr>' +
        '           </table>' +
        '           </div>' +
        '       </td>' +
        '   </tr>'
}
function createCalculatedFieldRowChoice(choiceName) {
    return '<tr>' +
        '       <td><input class="calculatedFieldRadio" type="radio" value="calculatedField" name="' + choiceName + '"></td>' +
        '       <td><span class="calculatedFieldRadioLabel">Calculated field</span></td>' +
        '       <td><div class="params">' +
        '           <table>' +
        '               <tr>' +
        '                   <td>Expression: </td>' +
        '                   <td><input id="paramExpression" type="text"></td>' +
        '               </tr>' +
        '           </table>' +
        '           </div>' +
        '       </td>' +
        '   </tr>'
}

function showBitPopulatorDialog(tag) {
    const choiceName = 'bitPopulator';
    $('#bitPopulatorDialog').empty().append($('<table></table>')
        .append(createFromAllRangeRowChoice(choiceName),
        createNullRowChoice(choiceName),
        createFromSourceRowChoice(choiceName)))
        .dialog('destroy')
        .dialog({modal:true
            ,title: 'Choose populator'
            ,width: 400
            ,buttons: {
                'Ok': function() {
                    var inp = $(this).find('input[name=' + choiceName + ']:radio:checked');
                    var label = inp.parents('tr').find('span');
                    var display = $('<input id="popType" type="text" readonly>').val(label.text());
                    var hidden = $('<input type="hidden">').val(inp.val());
                    var params = inp.parents('tr').find('.params').clone();
                    params.find('input').attr('readonly', true);
                    tag.empty();
                    tag.append(display, hidden, params);
                    $(this).dialog('close');
                },
                'Close' : function() {
                    $(this).dialog('close');
                }
            }
        });
}
function showIntPopulatorDialog(tag) {
    const choiceName = 'intPopulator';
    $('#intPopulatorDialog').empty().append($('<table></table>')
        .append(createFromAllRangeRowChoice(choiceName),
        createNullRowChoice(choiceName),
        createFromSourceRowChoice(choiceName)))
        .dialog('destroy')
        .dialog({modal:true
            ,title: 'Choose populator'
            ,width: 400
            ,buttons: {
                'Ok': function() {
                    var inp = $(this).find('input[name=' + choiceName + ']:radio:checked');
                    var label = inp.parents('tr').find('span');
                    var display = $('<input id="popType" type="text" readonly>').val(label.text());
                    var hidden = $('<input type="hidden">').val(inp.val());
                    var params = inp.parents('tr').find('.params').clone();
                    params.find('input').attr('readonly', true);
                    tag.empty();
                    tag.append(display, hidden, params);
                    $(this).dialog('close');
                },
                'Close' : function() {
                    $(this).dialog('close');
                }
            }
        });
}
function showFloatPopulatorDialog(tag) {
    const type = 'float';
    const choiceName = type + 'Populator';
    $('#' + type + 'PopulatorDialog').empty().append($('<table></table>')
        .append(createFromAllRangeRowChoice(choiceName),
        createNullRowChoice(choiceName),
        createFromSourceRowChoice(choiceName)))
        .dialog('destroy')
        .dialog({modal:true
            ,title: 'Choose populator'
            ,width: 400
            ,buttons: {
                'Ok': function() {
                    var inp = $(this).find('input[name=' + choiceName + ']:radio:checked');
                    var label = inp.parents('tr').find('span');
                    var display = $('<input id="popType" type="text" readonly>').val(label.text());
                    var hidden = $('<input type="hidden">').val(inp.val());
                    var params = inp.parents('tr').find('.params').clone();
                    params.find('input').attr('readonly', true);
                    tag.empty();
                    tag.append(display, hidden, params);
                    $(this).dialog('close');
                },
                'Close' : function() {
                    $(this).dialog('close');
                }
            }
        });
}
function showDatetimePopulatorDialog(tag) {
    const type = 'datetime';
    const choiceName = type + 'Populator';
    $('#' + type + 'PopulatorDialog').empty().append($('<table></table>')
        .append(createFromAllRangeRowChoice(choiceName),
        createNullRowChoice(choiceName),
        createFromSourceRowChoice(choiceName)))
        .dialog('destroy')
        .dialog({modal:true
            ,title: 'Choose populator'
            ,width: 400
            ,buttons: {
                'Ok': function() {
                    var inp = $(this).find('input[name=' + choiceName + ']:radio:checked');
                    var label = inp.parents('tr').find('span');
                    var display = $('<input id="popType" type="text" readonly>').val(label.text());
                    var hidden = $('<input type="hidden">').val(inp.val());
                    var params = inp.parents('tr').find('.params').clone();
                    params.find('input').attr('readonly', true);
                    tag.empty();
                    tag.append(display, hidden, params);
                    $(this).dialog('close');
                },
                'Close' : function() {
                    $(this).dialog('close');
                }
            }
        });
}
function showVarcharPopulatorDialog(tag) {
    const type = 'varchar';
    const choiceName = type + 'Populator';
    $('#' + type + 'PopulatorDialog').empty().append($('<table></table>')
        .append(createFromAllRangeRowChoice(choiceName),
        createNullRowChoice(choiceName),
        createFromSourceRowChoice(choiceName),
        createCalculatedFieldRowChoice(choiceName)))
        .dialog('destroy')
        .dialog({modal:true
            ,title: 'Choose populator'
            ,width: 400
            ,buttons: {
                'Ok': function() {
                    var inp = $(this).find('input[name=' + choiceName + ']:radio:checked');
                    var label = inp.parents('tr').find('span');
                    var display = $('<input id="popType" type="text" readonly>').val(label.text());
                    var hidden = $('<input type="hidden">').val(inp.val());
                    var params = inp.parents('tr').find('.params').clone();
                    params.find('input').attr('readonly', true);
                    tag.empty();
                    tag.append(display, hidden, params);
                    $(this).dialog('close');
                },
                'Close' : function() {
                    $(this).dialog('close');
                }
            }
        });
}

function createSelectPopulator(rowId) {
    var tag = $('<span></span>')
        .append('<input id="popType" type="text" value="From all range" readonly><input type="hidden" value="fromAllRange">');

    var button = $('<button>Change</button>')
        .click(function(event) {
            event.preventDefault();
            switch ($('#' + rowId + ' select > option:selected').val()) {
                case 'bit':
                    showBitPopulatorDialog(tag);
                    break;
                case 'int':
                    showIntPopulatorDialog(tag);
                    break;
                case 'float':
                    showFloatPopulatorDialog(tag);
                    break;
                case 'datetime':
                    showDatetimePopulatorDialog(tag);
                    break;
                case 'varchar':
                    showVarcharPopulatorDialog(tag);
                    break;
                default:
                    return;
            }
        });
    return $('<div></div>').append(tag).append(button);
}
function createDeleteButton(rowId) {
    return $('<button class="deleteRow" value="' + rowId + '">Delete</button>')
        .click(function(event) {
            event.preventDefault();
            $('#' + $(this).val()).remove();
            var columnCount = parseInt($('#columnCount').val());
            $('#columnCount').val(--columnCount);
        });
}
function addRow(rowId) {
    var row = $('<tr id="' + rowId + '"></tr>');
    var select = createSelectType();
    var populator = createSelectPopulator(rowId)
    var button = createDeleteButton(rowId);
    row.append('<td class="name"><input type="text"></td>')
        .append($('<td class="type"></td>').append(select))
        .append($('<td class="populator"></td>').append(populator))
        .append($('<td></td>').append(button));
    $('#rows').append(row);
}
$(document).ready(function () {
    $('#createColumns').click(function(event) {
        event.preventDefault();
        var columnCount = parseInt($('#columnCount').attr('readonly', true).val());
        for (var i = 0; i < columnCount; i++) {
            var rowId = 'row_' + i;
            addRow(rowId);
        }

        $('#colsDesc').removeClass("invisible");
        $('#createColumns').addClass("invisible");
        $('#addRow').removeClass("invisible");
        $('#generate').removeClass("invisible");

    });
    $('#addRow').click(function(event) {
        event.preventDefault();
        var columnCount = parseInt($('#columnCount').val());
        $('#columnCount').val(++columnCount);
        addRow('row_' + columnCount);
    });
    $('#generate').click(function(event) {
        event.preventDefault();
        var xml = $('<table></table>').wrap('<xml></xml>');
        xml.attr('name', $('#tableName').val());
        xml.attr('rowCount', $('#rowCount').val());
        $('#colsDesc > tbody > tr').each(function() {
            var populator = $('<populator></populator>')
                .attr('id', $(this).find('td.populator input:hidden').val());
            var params = $(this).find('td.populator .params input');
            if (params.length != 0) {
                params.each(function() {
                    if ($(this).is(':checkbox')) {
                        populator.append($('<parameter>' + $(this).prop('checked') + '</parameter>')
                            .attr('id', $(this).attr('id')));
                    } else
                        populator.append($('<parameter>' + $(this).val() + '</parameter>').attr('id', $(this).attr('id')));
                });
            }
            var column = $('<column></column>')
                .attr('name', $(this).find('td.name input').val())
                .attr('type', $(this).find('td.type select > option:selected').val())
                .append(populator);
            xml.append(column);
        });
        $('#log').text($('<div></div>').append(xml).html());
        $.ajax({
            url:'/generate',
            type: 'POST',
            success: function(data, textStatus, jqXHR) {
                $('#log').html($('<pre></pre>').text(data)).find('pre').snippet("sql", {style:'whatis'});
            },
            error: function(data, textStatus, jqXHR) {
                alert(data);
            },
            data:'xml=' + xml.parent().html()
        });
    });
});